package com.lsy.on_line.zaixian.service.impl;

import com.lsy.on_line.zaixian.Exception.ZXException;
import com.lsy.on_line.zaixian.mapper.*;
import com.lsy.on_line.zaixian.model.entity.*;
import com.lsy.on_line.zaixian.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ShiYuan
 * @since 2022-07-24
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private EpisodeMapper episodeMapper;
    @Autowired
    private PlayRecordMapper playRecordMapper;

    /**
     * 下单
     * @param userId
     * @param videoId
     * @return
     */
    @Override
    @Transactional//绑定事务
    public int save(int userId, int videoId) {
        //判断已购买不可重复购买
        Order order = orderMapper.findByUserIdAndVideoIdAndState(userId,videoId,1);
        if(order != null){
            return 0;
        }
        Video video = videoMapper.findById(videoId);//根据id查询视频详情
        Order newOrder = new Order();//创建订单对象
        newOrder.setCreateTime(new Date());//获取下单时间
        newOrder.setOutTradeNo(UUID.randomUUID().toString());//随机生成订单编号
        newOrder.setState(1);//设置购买状态1为已经购买
        newOrder.setTotalFee(video.getPrice());//获取价格计算总费用
        newOrder.setUserId(userId);//当前下单是哪个用户
        newOrder.setVideoId(videoId);//下单的那个视频
        newOrder.setVideoImg(video.getCoverImg());//获取封面图设置视频图片
        newOrder.setVideoTitle(video.getTitle());//获取标题设置视频标题

        int rows = orderMapper.saveOrder(newOrder);//保存订单信息

        //生成播放记录(在成功购买课程时就开始创建播放记录)
        if(rows == 1){
            Episode exception = episodeMapper.findFirstEpisodeByVideoId(videoId);//根据视频id查询当前播放到第几集
            if(exception == null){
                throw new ZXException(-1,"该视频没有集信息,请运营人员检查相关信息");
            }
            PlayRecord playRecord = new PlayRecord();//创建播放记录表对象
            playRecord.setCreateTime(new Date());//设置开始播放时间
            playRecord.setEpisodeId(exception.getId());//设置插入视频id
            playRecord.setCurrentNum(exception.getNum());//设置当前视频数量
            playRecord.setUserId(userId);//设置用户id
            playRecord.setVideoId(videoId);//设置视频id
            playRecordMapper.saveRecord(playRecord);
        }
        return rows;
    }

    /**
     * 根据userId获取订单列表
     * @param userId
     * @return
     */
    @Override
    public List<Order> listOrderByUserId(Integer userId) {

        List<Order> orderList = orderMapper.findOrderListBuUserId(userId);

        return orderList;
    }
}
